package com.woyao.core.util;

import android.app.Dialog;
import android.content.ContentUris;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.graphics.Color;
import android.media.MediaMetadataRetriever;
import android.net.Uri;
import android.os.AsyncTask;
import android.os.Build;
import android.os.Environment;
import android.provider.DocumentsContract;
import android.provider.MediaStore;
import android.provider.Settings;
import android.support.design.internal.BottomNavigationItemView;
import android.support.design.internal.BottomNavigationMenuView;
import android.support.design.widget.BottomNavigationView;
import android.support.design.widget.Snackbar;
import android.support.v4.content.ContextCompat;
import android.support.v7.app.AlertDialog;
import android.util.Log;
import android.view.GestureDetector;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.widget.Button;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.alibaba.sdk.android.oss.ClientException;
import com.alibaba.sdk.android.oss.OSS;
import com.alibaba.sdk.android.oss.ServiceException;
import com.alibaba.sdk.android.oss.callback.OSSCompletedCallback;
import com.alibaba.sdk.android.oss.callback.OSSProgressCallback;
import com.alibaba.sdk.android.oss.internal.OSSAsyncTask;
import com.alibaba.sdk.android.oss.model.PutObjectRequest;
import com.alibaba.sdk.android.oss.model.PutObjectResult;
import com.squareup.picasso.Picasso;
import com.woyao.PlayVideoActivity;
import com.woyao.R;
import com.woyao.ShowImageActivity;
import com.woyao.VideoSnapTask;
import com.woyao.WoyaoooApplication;
import com.woyao.core.FileUtil;
import com.woyao.core.model.BaseResponse;
import com.woyao.core.model.KeyValue;
import com.woyao.core.model.MediaSummary;
import com.woyao.core.service.AccountService;

import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.lang.reflect.Field;
import java.nio.ByteBuffer;
import java.nio.ByteOrder;
import java.nio.ShortBuffer;
import java.nio.channels.FileChannel;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Locale;
import java.util.Random;

import retrofit2.Call;

/**
 * Created by Administrator on 2016/9/20 0020.
 */
public class Common {


    public static final String defaultpic =  "https://www.woyaooo.com/static/images/icon175x175.jpeg";




//
//
//    /**
//     * 分享网页类型至微信
//     *
//     * @param context 上下文
//     * @param appId   微信的appId
//     * @param webUrl  网页的url
//     * @param title   网页标题
//     * @param content 网页描述
//     * @param bitmap  位图
//     */
//    public static void shareWeb(Context context, String appId, String webUrl, String title, String content, Bitmap bitmap) {
//        // 通过appId得到IWXAPI这个对象
//        IWXAPI wxapi = WXAPIFactory.createWXAPI(context, appId);
//        // 检查手机或者模拟器是否安装了微信
//        if (!wxapi.isWXAppInstalled()) {
//
//            return;
//        }
//
//        // 初始化一个WXWebpageObject对象
//        WXWebpageObject webpageObject = new WXWebpageObject();
//        // 填写网页的url
//        webpageObject.webpageUrl = webUrl;
//
//        // 用WXWebpageObject对象初始化一个WXMediaMessage对象
//        WXMediaMessage msg = new WXMediaMessage(webpageObject);
//        // 填写网页标题、描述、位图
//        msg.title = title;
//        msg.description = content;
//        // 如果没有位图，可以传null，会显示默认的图片
//        msg.setThumbImage(bitmap);
//
//        // 构造一个Req
//        SendMessageToWX.Req req = new SendMessageToWX.Req();
//        // transaction用于唯一标识一个请求（可自定义）
//        req.transaction = "webpage";
//        // 上文的WXMediaMessage对象
//        req.message = msg;
//        // SendMessageToWX.Req.WXSceneSession是分享到好友会话
//        // SendMessageToWX.Req.WXSceneTimeline是分享到朋友圈
//        req.scene = SendMessageToWX.Req.WXSceneSession;
//
//        // 向微信发送请求
//        wxapi.sendReq(req);
//    }

    public static  Integer getVisitUserid( ){
        int min = 100000000;
        int max = 999999999;
        return new Random().nextInt(max-min)+min ;

    }

    public static String getDateStr(){
        SimpleDateFormat formatter   =   new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        Date curDate   =   new Date(System.currentTimeMillis());//获取当前时间
        String   strDate   =   formatter.format(curDate);
        return strDate;
    }

//
//https://blog.csdn.net/lxy_tap/article/details/74567282
//    MediaRecorderUtil mrUtil=new MediaRecorderUtil();
//mrUtil.recorderStart();
//    三、音视频合成
//
////aacPath录音的文件路径、mp4Path原视频路径、outPath合成之后输出的视频文件路径
//
//    boolean flag=Mp4ParseUtil.muxAacMp4(aacPath,mp4Path,outPath);
//    四、视频拼接
//
////mMp4List视频拼接的路径集合、outPath拼接成功的视频输出路径
//
//Mp4ParseUtil.appendMp4List(mMp4List,outPath);
//    大致就这样了
    public static synchronized void cutMp4(final long startTime, final long endTime, final String FilePath, final String WorkingPath, final String fileName){
        new Thread(new Runnable() {
            @Override
            public void run() {

                try{
                    //视频剪切
                    VideoClip videoClip= new VideoClip();//实例化VideoClip类
                    videoClip.setFilePath(FilePath);//设置被编辑视频的文件路径  FileUtil.getMediaDir()+"/test/laoma3.mp4"
                    videoClip.setWorkingPath(WorkingPath);//设置被编辑的视频输出路径  FileUtil.getMediaDir()
                    videoClip.setStartTime(startTime);//设置剪辑开始的时间
                    videoClip.setEndTime(endTime);//设置剪辑结束的时间
                    videoClip.setOutName(fileName);//设置输出的文件名称
                    videoClip.clip();//调用剪辑并保存视频文件方法（建议作为点击保存时的操作并加入等待对话框）

                }catch (Exception e){
                    e.printStackTrace();
                }
            }
        }).start();
    }

    public static String getPath(final Context context, final Uri uri) {

        final boolean isKitKat = Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT;

        // MediaStore (and general)

        // DocumentProvider
        if (isKitKat && DocumentsContract.isDocumentUri(context, uri)) {
            // ExternalStorageProvider
            if (isExternalStorageDocument(uri)) {
                final String docId = DocumentsContract.getDocumentId(uri);
                final String[] split = docId.split(":");
                final String type = split[0];

                if ("primary".equalsIgnoreCase(type)) {
                    return Environment.getExternalStorageDirectory() + "/" + split[1];
                }

                // TODO handle non-primary volumes
            }
            // DownloadsProvider
            else if (isDownloadsDocument(uri)) {

                final String id = DocumentsContract.getDocumentId(uri);
                final Uri contentUri = ContentUris.withAppendedId(
                        Uri.parse("content://downloads/public_downloads"), Long.valueOf(id));

                return getDataColumn(context, contentUri, null, null);
            }
            // MediaProvider
            else if (isMediaDocument(uri)) {
                final String docId = DocumentsContract.getDocumentId(uri);
                final String[] split = docId.split(":");
                final String type = split[0];

                Uri contentUri = null;
                if ("image".equals(type)) {
                    contentUri = MediaStore.Images.Media.EXTERNAL_CONTENT_URI;
                } else if ("video".equals(type)) {
                    contentUri = MediaStore.Video.Media.EXTERNAL_CONTENT_URI;
                } else if ("audio".equals(type)) {
                    contentUri = MediaStore.Audio.Media.EXTERNAL_CONTENT_URI;
                }

                final String selection = "_id=?";
                final String[] selectionArgs = new String[] {
                        split[1]
                };

                return getDataColumn(context, contentUri, selection, selectionArgs);
            }
        }else if ("content".equalsIgnoreCase(uri.getScheme())) {
            return getDataColumn(context, uri, null, null);
        }
        // File
        else if ("file".equalsIgnoreCase(uri.getScheme())) {
            return uri.getPath();
        }


        return null;
    }

    /**
     * Get the value of the data column for this Uri. This is useful for
     * MediaStore Uris, and other file-based ContentProviders.
     *
     * @param context The context.
     * @param uri The Uri to query.
     * @param selection (Optional) Filter used in the query.
     * @param selectionArgs (Optional) Selection arguments used in the query.
     * @return The value of the _data column, which is typically a file path.
     */
    public static String getDataColumn(Context context, Uri uri, String selection,
                                       String[] selectionArgs) {

        Cursor cursor = null;
        final String column = "_data";
        final String[] projection = {
                column
        };

        try {
            cursor = context.getContentResolver().query(uri, projection, selection, selectionArgs,
                    null);
            if (cursor != null && cursor.moveToFirst()) {
                final int column_index = cursor.getColumnIndexOrThrow(column);
                return cursor.getString(column_index);
            }
        } finally {
            if (cursor != null)
                cursor.close();
        }
        return null;
    }


    /**
     * @param uri The Uri to check.
     * @return Whether the Uri authority is ExternalStorageProvider.
     */
    public static boolean isExternalStorageDocument(Uri uri) {
        return "com.android.externalstorage.documents".equals(uri.getAuthority());
    }

    /**
     * @param uri The Uri to check.
     * @return Whether the Uri authority is DownloadsProvider.
     */
    public static boolean isDownloadsDocument(Uri uri) {
        return "com.android.providers.downloads.documents".equals(uri.getAuthority());
    }

    /**
     * @param uri The Uri to check.
     * @return Whether the Uri authority is MediaProvider.
     */
    public static boolean isMediaDocument(Uri uri) {
        return "com.android.providers.media.documents".equals(uri.getAuthority());
    }

    public static String getVideoSnapFile( String videoPath ,Context context) {

        Bitmap bm = retriveVideoFrameFromVideo( videoPath);

        String filename = videoPath.substring(videoPath.lastIndexOf("/")+1) +".png";

        return  "file://" + compressImage(bm , getDiskCachePath( context) +"/" + filename) ;
    }



    public static Bitmap retriveVideoFrameFromVideo(String videoPath)
    {
        Bitmap bitmap = null;
        MediaMetadataRetriever mediaMetadataRetriever = null;
        try
        {
            mediaMetadataRetriever = new MediaMetadataRetriever();
            if (Build.VERSION.SDK_INT >= 14)
                mediaMetadataRetriever.setDataSource(videoPath, new HashMap<String, String>());
            else
                mediaMetadataRetriever.setDataSource(videoPath);
            //   mediaMetadataRetriever.setDataSource(videoPath);
            bitmap = mediaMetadataRetriever.getFrameAtTime( ( 1000 + 1L), MediaMetadataRetriever.OPTION_CLOSEST_SYNC );
        }
        catch (Exception e)
        {
            e.printStackTrace();
//            throw new Throwable(
//                    "Exception in retriveVideoFrameFromVideo(String videoPath)"
//                            + e.getMessage());

        }
        finally
        {
            if (mediaMetadataRetriever != null)
            {
                mediaMetadataRetriever.release();
            }
        }
        return bitmap;
    }


    public static String compressImage(Bitmap bitmap, String filename) {
        if (bitmap == null ) {
            return defaultpic;
        }
        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        bitmap.compress(Bitmap.CompressFormat.JPEG, 100, baos);//质量压缩方法，这里100表示不压缩，把压缩后的数据存放到baos中
        int options = 100;
        while (baos.toByteArray().length / 1024 > 500) {  //循环判断如果压缩后图片是否大于500kb,大于继续压缩
            baos.reset();//重置baos即清空baos
            options -= 10;//每次都减少10
            bitmap.compress(Bitmap.CompressFormat.JPEG, options, baos);//这里压缩options%，把压缩后的数据存放到baos中
            long length = baos.toByteArray().length;
        }

        File file = new File( filename);
        try {
            FileOutputStream fos = new FileOutputStream(file);
            try {
                fos.write(baos.toByteArray());
                fos.flush();
                fos.close();
            } catch (IOException e) {
                e.printStackTrace();
                return defaultpic;
            }
        } catch (FileNotFoundException e) {
            e.printStackTrace();
            return defaultpic;
        }
        bitmap.recycle();
        return file.getPath();
    }

    public static void swapEndian( String infile , String outfile){
        try{
            FileInputStream fs = new FileInputStream(infile);
            FileChannel fc = fs.getChannel();
            ByteBuffer byteBuffer = ByteBuffer.allocate((int)fc.size());
            byteBuffer.order(ByteOrder.LITTLE_ENDIAN);
            fc.read(byteBuffer);
            byteBuffer.flip();

            ShortBuffer buffer = byteBuffer.asShortBuffer();
            short[] shortArray = new short[(int)fc.size()/2];
            buffer.get(shortArray);

            byteBuffer.clear();
            byteBuffer.order(ByteOrder.BIG_ENDIAN);
            ShortBuffer shortOutputBuffer = byteBuffer.asShortBuffer();
            shortOutputBuffer.put(shortArray);

            FileChannel out = new FileOutputStream(outfile).getChannel();
            out.write(byteBuffer);
            out.close();

//            FileInputStream fs = new FileInputStream(infile);
//            FileChannel fc = fs.getChannel();
//
//            File file = new File(outfile);
//            FileOutputStream outStream = new FileOutputStream(file,false);
//
//            ByteBuffer buf = ByteBuffer.allocate(0x10000);
//            buf.order(ByteOrder.LITTLE_ENDIAN); // or ByteOrder.BIG_ENDIAN   LITTLE_ENDIAN
//            int len = 0;
//            while((len = fc.read(buf)) != -1){
//
//
//                outStream.write(buf.array(), 0, len);
//            }
//
//            outStream.close();
        } catch (Exception e) {
            e.printStackTrace();
        }

    }


    public static void alert( Context context, String message){

        Dialog alertDialog = new AlertDialog.Builder(context).
                setTitle("信息").
                setMessage(message).
                setIcon(R.drawable.ic_launcher).
                setPositiveButton("确定", new DialogInterface.OnClickListener() {

                    @Override
                    public void onClick(DialogInterface dialog, int which) {

                    }
                }).
                create();
        alertDialog.show();
    }

    public static String getDiskCachePath(Context context) {
        if (Environment.MEDIA_MOUNTED.equals(Environment.getExternalStorageState()) || !Environment.isExternalStorageRemovable()) {
            return context.getExternalCacheDir().getPath();
        } else {
            return context.getCacheDir().getPath();
        }
    }

    public static void uploadFile( Context context ,String filename,final String picturePath ){

        OSS oss = FileUtil.getOss( context );
        PutObjectRequest put = new PutObjectRequest(FileUtil.bucketName, filename, picturePath);

// 异步上传时可以设置进度回调
        put.setProgressCallback(new OSSProgressCallback<PutObjectRequest>() {
            @Override
            public void onProgress(PutObjectRequest request, long currentSize, long totalSize) {

            }
        });

        OSSAsyncTask task = oss.asyncPutObject(put, new OSSCompletedCallback<PutObjectRequest, PutObjectResult>() {
            @Override
            public void onSuccess(PutObjectRequest request, PutObjectResult result) {
                Log.i("haiming","uploaded " + picturePath );
            }

            @Override
            public void onFailure(PutObjectRequest request, ClientException clientExcepion, ServiceException serviceException) {
                // 请求异常
                if (clientExcepion != null) {
                    // 本地异常如网络异常等
                    clientExcepion.printStackTrace();
                }
                if (serviceException != null) {
                    // 服务异常

                }
            }
        });

    }

    public static   List<KeyValue>   StringToKeyValue(ArrayList<String> hows) {
        List<KeyValue> ret = new ArrayList<KeyValue>() ;
        for (String howww : hows) {
            KeyValue kv = new KeyValue();
            kv.setNo(howww);
            kv.setName(howww);
            ret.add(kv);
        }
        return  ret;
    }

    public static String getCurrentVersion(Context ctx) {
        try {

            PackageManager manager = ctx.getPackageManager();
            PackageInfo info = manager.getPackageInfo(ctx.getPackageName(), 0);

            Log.e("woyaooo", "当前版本名和版本号" + info.versionName + "--" + info.versionCode);

            return info.versionName;
        } catch (Exception e) {
            e.printStackTrace();

            Log.e("woyaooo", "获取当前版本号出错");
            return "";
        }
    }
    /**
     * 获取当前手机系统语言。
     *
     * @return 返回当前系统语言。例如：当前设置的是“中文-中国”，则返回“zh-CN”
     */
    public static String getSystemLanguage() {
        return Locale.getDefault().getLanguage();
    }

    /**
     * 获取当前系统上的语言列表(Locale列表)
     *
     * @return  语言列表
     */
    public static Locale[] getSystemLanguageList() {
        return Locale.getAvailableLocales();
    }

    /**
     * 获取当前手机系统版本号
     *
     * @return  系统版本号
     */
    public static String getSystemVersion() {
        return android.os.Build.VERSION.RELEASE;
    }

    /**
     * 获取手机型号
     *
     * @return  手机型号
     */
    public static String getSystemModel() {
        return android.os.Build.MODEL;
    }

    /**
     * 获取手机厂商
     *
     * @return  手机厂商
     */
    public static String getDeviceBrand() {
        return android.os.Build.BRAND;
    }

    /**
     * 获取手机IMEI(需要“android.permission.READ_PHONE_STATE”权限)
     *
     * @return  手机IMEI
     */
    public static String getDeviceID(Context ctx) {
        String ret = "";
//        try {
//            TelephonyManager tm = (TelephonyManager) ctx.getSystemService(Activity.TELEPHONY_SERVICE);
//            if (tm != null){
//                if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
//                    ret = tm.getImei();
//                }else{
//                    ret = tm.getDeviceId();
//                }
//            }
//
//        }catch(SecurityException se){
//
//        }

        ret = Settings.System.getString(ctx.getContentResolver(), Settings.System.ANDROID_ID);

        if (ret == null){
            ret = "";
        }
        return ret;

    }

    public static   void   showSnack(Context ctt,View v, String content ) {
        Snackbar sb = Snackbar.make(v,content, Snackbar.LENGTH_SHORT);

        View view = sb.getView();
        view.setBackgroundColor(ContextCompat.getColor(ctt, R.color.colorPrimary));

        TextView tv = (TextView) view.findViewById(R.id.snackbar_text);
        tv.setTextColor(Color.WHITE);
        sb.show();
    }

    public static  void reportError( final Integer user_id, final String errorType,final String activity, final String title, final String desc){
        final String themobile = Common.getSystemModel() + "#" + Common.getSystemVersion() +"#";
        AsyncTask<Void, Void, Boolean> task = new AsyncTask<Void, Void, Boolean>() {
            @Override
            protected Boolean doInBackground(Void... params) {
                AccountService svc = ServiceFactory.get(AccountService.class);
                Call<BaseResponse> responseCall = svc.reportError(WoyaoooApplication.userId,errorType,activity,title,themobile + desc);
                Boolean ret = true ;
                try {
                    BaseResponse response = responseCall.execute().body();
                    ret= response.isSuccess();
                } catch (IOException e) {
                    e.printStackTrace();
                    ret = false;
                }
                return ret;
            }

            @Override
            protected void onPostExecute(final Boolean success) {
                if (success) {

                } else {

                }
            }

            @Override
            protected void onCancelled() {
            }
        };
        task.execute((Void) null);

    }

    public static  void setProfileAttr( final String att, final String content){
        AsyncTask<Void, Void, Boolean> task = new AsyncTask<Void, Void, Boolean>() {
            @Override
            protected Boolean doInBackground(Void... params) {
                AccountService svc = ServiceFactory.get(AccountService.class);
                Call<BaseResponse> responseCall = svc.setProfileAttr(WoyaoooApplication.userId,att,content);
                Boolean ret = true ;
                try {
                    BaseResponse response = responseCall.execute().body();
                    ret= response.isSuccess();
                } catch (IOException e) {
                    e.printStackTrace();
                    ret = false;
                }
                return ret;
            }

            @Override
            protected void onPostExecute(final Boolean success) {
                if (success) {

                } else {

                }
            }

            @Override
            protected void onCancelled() {
            }
        };
        task.execute((Void) null);

    }


    public static  void setConcensusAttrFeedback(final Context context,final Integer id, final String att, final String content){
        AsyncTask<Void, Void, BaseResponse> task = new AsyncTask<Void, Void, BaseResponse>() {
            @Override
            protected BaseResponse doInBackground(Void... params) {
                AccountService svc = ServiceFactory.get(AccountService.class);
                Call<BaseResponse> responseCall = svc.setConcensusAttr(WoyaoooApplication.userId,id,att,content);
                BaseResponse ret = null ;
                try {
                    ret = responseCall.execute().body();
                } catch (IOException e) {
                    e.printStackTrace();
                    ret = null;
                }
                return ret;
            }

            @Override
            protected void onPostExecute(final BaseResponse response) {
                if (response != null) {
                    if ( ! response.getMessage().equals("") ) {
                        alert(context,response.getMessage());
                    }
                } else {
                    alert( context,"系统发生错误");
                }
            }

            @Override
            protected void onCancelled() {
            }
        };
        task.execute((Void) null);

    }

    public static  void setCommentAttrFeedback(final Context context,final Integer id, final String att, final String content){
        AsyncTask<Void, Void, BaseResponse> task = new AsyncTask<Void, Void, BaseResponse>() {
            @Override
            protected BaseResponse doInBackground(Void... params) {
                AccountService svc = ServiceFactory.get(AccountService.class);
                Call<BaseResponse> responseCall = svc.setCommentAttr(WoyaoooApplication.userId,id,att,content);
                BaseResponse ret = null ;
                try {
                    ret = responseCall.execute().body();
                } catch (IOException e) {
                    e.printStackTrace();
                    ret = null;
                }
                return ret;
            }

            @Override
            protected void onPostExecute(final BaseResponse response) {
                if (response != null) {
                    if ( ! response.getMessage().equals("") ) {
                        alert(context,response.getMessage());
                    }
                } else {
                    alert( context,"系统发生错误");
                }
            }

            @Override
            protected void onCancelled() {
            }
        };
        task.execute((Void) null);

    }


    public static  void setProfileAttrFeedback(final Context context, final String att, final String content){
        AsyncTask<Void, Void, BaseResponse> task = new AsyncTask<Void, Void, BaseResponse>() {
            @Override
            protected BaseResponse doInBackground(Void... params) {
                AccountService svc = ServiceFactory.get(AccountService.class);
                Call<BaseResponse> responseCall = svc.setProfileAttr(WoyaoooApplication.userId,att,content);
                BaseResponse ret = null ;
                try {
                    ret = responseCall.execute().body();
                } catch (IOException e) {
                    e.printStackTrace();
                    ret = null;
                }
                return ret;
            }

            @Override
            protected void onPostExecute(final BaseResponse response) {
                if (response != null) {
                    if ( ! response.getMessage().equals("") ) {
                        alert(context,response.getMessage());
                    }
                } else {
                    alert( context,"系统发生错误");
                }
            }

            @Override
            protected void onCancelled() {
            }
        };
        task.execute((Void) null);

    }

    public static  void setDemandAttrFeedback(final Context context, final Integer id, final String att, final String content) {
        AsyncTask<Void, Void, BaseResponse> task = new AsyncTask<Void, Void, BaseResponse>() {
            @Override
            protected BaseResponse doInBackground(Void... params) {
                AccountService svc = ServiceFactory.get(AccountService.class);
                Call<BaseResponse> responseCall = svc.setDemandAttr(WoyaoooApplication.userId,id,att,content,"");
                BaseResponse ret = null ;
                try {
                    ret = responseCall.execute().body();
                } catch (IOException e) {
                    e.printStackTrace();
                }
                return ret;
            }

            @Override
            protected void onPostExecute(final BaseResponse response) {
                if (response != null) {
                    if ( ! response.getMessage().equals("") ) {
                        alert(context,response.getMessage());
                    }
                } else {
                    alert( context,"系统发生错误");
                }
            }

            @Override
            protected void onCancelled() {
            }
        };
        task.execute((Void) null);
    }

    public static  void setDemandAttr( final Integer id, final String att, final String content) {
        setDemandAttr(  id,  att,  content ,"");
    }

    public static  void setDemandAttr( final Integer id, final String att, final String content, final String act){
        AsyncTask<Void, Void, Boolean> task = new AsyncTask<Void, Void, Boolean>() {
            @Override
            protected Boolean doInBackground(Void... params) {
                AccountService svc = ServiceFactory.get(AccountService.class);
                Call<BaseResponse> responseCall = svc.setDemandAttr(WoyaoooApplication.userId,id,att,content,act);
                Boolean ret = true ;
                try {
                    BaseResponse response = responseCall.execute().body();
                    ret= response.isSuccess();
                } catch (IOException e) {
                    e.printStackTrace();
                    ret = false;
                }
                return ret;
            }

            @Override
            protected void onPostExecute(final Boolean success) {
                if (success) {

                } else {

                }
            }

            @Override
            protected void onCancelled() {
            }
        };
        task.execute((Void) null);

    }

    public static  void setMemberAttr( final Integer id, final String att, final String content){
        AsyncTask<Void, Void, Boolean> task = new AsyncTask<Void, Void, Boolean>() {
            @Override
            protected Boolean doInBackground(Void... params) {
                AccountService svc = ServiceFactory.get(AccountService.class);
                Call<BaseResponse> responseCall = svc.setMemberAttr(WoyaoooApplication.userId,id,att,content);
                Boolean ret = true ;
                try {
                    BaseResponse response = responseCall.execute().body();
                    ret= response.isSuccess();
                } catch (IOException e) {
                    e.printStackTrace();
                    ret = false;
                }
                return ret;
            }

            @Override
            protected void onPostExecute(final Boolean success) {
                if (success) {

                } else {

                }
            }

            @Override
            protected void onCancelled() {
            }
        };
        task.execute((Void) null);

    }


    public static  void setOrgAttr( final Integer id, final String att, final String content){
        AsyncTask<Void, Void, Boolean> task = new AsyncTask<Void, Void, Boolean>() {
            @Override
            protected Boolean doInBackground(Void... params) {
                AccountService svc = ServiceFactory.get(AccountService.class);
                Call<BaseResponse> responseCall = svc.setOrgAttr(WoyaoooApplication.userId,id,att,content);
                Boolean ret = true ;
                try {
                    BaseResponse response = responseCall.execute().body();
                    ret= response.isSuccess();
                } catch (IOException e) {
                    e.printStackTrace();
                    ret = false;
                }
                return ret;
            }

            @Override
            protected void onPostExecute(final Boolean success) {
                if (success) {

                } else {

                }
            }

            @Override
            protected void onCancelled() {
            }
        };
        task.execute((Void) null);

    }


    public static  void setRelationAttr( final Integer id,final Integer mid, final String att, final String content){
        AsyncTask<Void, Void, Boolean> task = new AsyncTask<Void, Void, Boolean>() {
            @Override
            protected Boolean doInBackground(Void... params) {
                AccountService svc = ServiceFactory.get(AccountService.class);
                Call<BaseResponse> responseCall = svc.setRelationAttr(WoyaoooApplication.userId,id,mid,att,content);
                Boolean ret = true ;
                try {
                    BaseResponse response = responseCall.execute().body();
                    ret= response.isSuccess();
                } catch (IOException e) {
                    e.printStackTrace();
                    ret = false;
                }
                return ret;
            }

            @Override
            protected void onPostExecute(final Boolean success) {
                if (success) {

                } else {

                }
            }

            @Override
            protected void onCancelled() {
            }
        };
        task.execute((Void) null);

    }

    public static  void setRelationAttrFeedback(final Context context, final Integer id,final Integer mid, final String att, final String content){
        AsyncTask<Void, Void, BaseResponse> task = new AsyncTask<Void, Void, BaseResponse>() {
            @Override
            protected BaseResponse doInBackground(Void... params) {
                AccountService svc = ServiceFactory.get(AccountService.class);
                Call<BaseResponse> responseCall = svc.setRelationAttr(WoyaoooApplication.userId,id,mid,att,content);
                BaseResponse response = null ;
                try {
                    response = responseCall.execute().body();

                } catch (IOException e) {
                    e.printStackTrace();
                }
                return response;
            }

            @Override
            protected void onPostExecute(final BaseResponse response) {
                if (response != null) {
                    if ( ! response.getMessage().equals("") ) {
                        alert(context,response.getMessage());
                    }
                } else {
                    alert( context,"系统发生错误");
                }
            }

            @Override
            protected void onCancelled() {
            }
        };
        task.execute((Void) null);

    }

    public static  void setContactAttr( final String id, final String att, final String content){
        AsyncTask<Void, Void, Boolean> task = new AsyncTask<Void, Void, Boolean>() {
            @Override
            protected Boolean doInBackground(Void... params) {
                AccountService svc = ServiceFactory.get(AccountService.class);
                Call<BaseResponse> responseCall = svc.setContactAttr(WoyaoooApplication.userId,id,att,content);
                Boolean ret = true ;
                try {
                    BaseResponse response = responseCall.execute().body();
                    ret= response.isSuccess();
                } catch (IOException e) {
                    e.printStackTrace();
                    ret = false;
                }
                return ret;
            }

            @Override
            protected void onPostExecute(final Boolean success) {
                if (success) {

                } else {

                }
            }

            @Override
            protected void onCancelled() {
            }
        };
        task.execute((Void) null);

    }


    public static  void setInquiryAttrFeedback(final Context context, final Integer id, final String att, final String content) {
        AsyncTask<Void, Void, BaseResponse> task = new AsyncTask<Void, Void, BaseResponse>() {
            @Override
            protected BaseResponse doInBackground(Void... params) {
                AccountService svc = ServiceFactory.get(AccountService.class);
                Call<BaseResponse> responseCall = svc.setInquiryAttr(WoyaoooApplication.userId,id,att,content);
                BaseResponse ret = null ;
                try {
                    ret = responseCall.execute().body();
                } catch (IOException e) {
                    e.printStackTrace();
                }
                return ret;
            }

            @Override
            protected void onPostExecute(final BaseResponse response) {
                if (response != null) {
                    if ( ! response.getMessage().equals("") ) {
                        alert(context,response.getMessage());
                    }
                } else {
                    alert( context,"系统发生错误");
                }
            }

            @Override
            protected void onCancelled() {
            }
        };
        task.execute((Void) null);
    }
    public static String listToString(List<String> stringList){
        if (stringList==null) {
            return null;
        }
        StringBuilder result=new StringBuilder();
        boolean flag=false;
        for (String string : stringList) {
            if (flag) {
                result.append(",");
            }else {
                flag=true;
            }
            result.append(string);
        }
        return result.toString();
    }

    public static String ListToString(ArrayList<String> thelist){

        StringBuilder result=new StringBuilder();
        boolean flag=false;
        for (String theone : thelist) {
            if (flag) {
                result.append(",");
            }else {
                flag=true;
            }
            result.append(theone);
        }
        return result.toString();
    }

    public static String getMediaIds(ArrayList<MediaSummary> thedata) {
        StringBuilder result = new StringBuilder();
        boolean flag = false;
        for (
                MediaSummary theone : thedata) {
            if (flag) {
                result.append(",");
            } else {
                flag = true;
            }
            result.append(theone.getId());
        }
        return result.toString();
    }
    public static String KeyValueToNames(List<KeyValue> thelist){

        StringBuilder result=new StringBuilder();
        boolean flag=false;
        for (KeyValue theone : thelist) {
            if (flag) {
                result.append(",");
            }else {
                flag=true;
            }
            result.append(theone.getName());
        }
        return result.toString();
    }

    public static String KeyValueToNos(List<KeyValue> thelist){

        StringBuilder result=new StringBuilder();
        boolean flag=false;
        for (KeyValue theone : thelist) {
            if (flag) {
                result.append(",");
            }else {
                flag=true;
            }
            result.append(theone.getNo());
        }
        return result.toString();
    }

    private static Common ourInstance = new Common();

    public static Common getInstance() {
        return ourInstance;
    }

    private Common() {
    }

    public static void enableZoom(final Context context, ImageView demandPic, final String picpath ){
        GestureDetector.SimpleOnGestureListener getLis = new GestureDetector.SimpleOnGestureListener();
        final GestureDetector gestureDetector = new GestureDetector(context,getLis);

        gestureDetector.setOnDoubleTapListener(new GestureDetector.OnDoubleTapListener() {
            @Override
            public boolean onSingleTapConfirmed(MotionEvent e) {
                return false;
            }

            @Override
            public boolean onDoubleTap(MotionEvent e) {
                Intent intent = new Intent();
                intent.setClass(context, ShowImageActivity.class);
                intent.putExtra("image",  picpath );
                context.startActivity(intent);
                return false;
            }

            @Override
            public boolean onDoubleTapEvent(MotionEvent e) {
                return false;
            }
        });


        demandPic.setOnTouchListener(new View.OnTouchListener() {
            @Override
            public boolean onTouch(View v, MotionEvent event) {

//                gestureDetector.onTouchEvent( event);
//                Intent intent = new Intent();
//                intent.setClass(ChanceActivity.this, ShowImageActivity.class);
//                intent.putExtra("image",  chance.getImage() );
//                startActivity(intent);
                return gestureDetector.onTouchEvent(event);
            }
        });
        demandPic.setClickable(true);
        demandPic.setFocusable(true);
        demandPic.setLongClickable(true);
    }


    public static void  showMP4( final Context context, final String videoPath ,final ImageView imageView ){

        VideoSnapTask task = new VideoSnapTask(videoPath, context, new VideoSnapTask.Callback() {
            @Override
            public void onSnapCompleted(String imagePath) {
                Picasso.with(context)
                        .load(imagePath)
                        .into(imageView );
            }

            @Override
            public void onError(Exception e) {
                // 处理错误
                 Toast.makeText(context, "加载视频出错 ", Toast.LENGTH_SHORT).show();
            }
        });
        task.execute();
    }

    public static ImageView  showMainMedia( final Context context, final String onepic , LinearLayout pics ) {

        FrameLayout item = (FrameLayout) LayoutInflater.from(context).inflate(R.layout.mainimage_item, null);
        ImageView imageView  = (ImageView)item.findViewById(R.id.pic);
        Button playBtn  = (Button)item.findViewById(R.id.video_play);

        if (!StringUtil.notNullOrEmpty(onepic)) {

            return imageView;
        }


        String imagePath = "";
        if (onepic.endsWith( "mp4")) {
//            imagePath = Common.getVideoSnapFile( onepic, context);
            showMP4(context,onepic,imageView);
            playBtn.setVisibility( View.VISIBLE);
            playBtn.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    Intent intent = new Intent();
                    intent.setClass(context, PlayVideoActivity.class);
                    intent.putExtra("path", onepic );
                    context.startActivity(intent );
                }
            });
        }else {
            imagePath =  onepic;
//            imageView.setOnLongClickListener(new View.OnLongClickListener() {
//                @Override
//                public boolean onLongClick(View view) {
//
//                    Intent intent = new Intent();
//                    intent.setClass(context, WebviewActivity.class);
//                    intent.putExtra("link", onepic);
//                    context.startActivity(intent);
//                    return false;
//                }
//            });

            Common.enableZoom(context,imageView,onepic);
            playBtn.setVisibility( View.GONE);
            Picasso.with(context)
                    .load(imagePath)
                    .into(imageView );
        }

        pics.addView(item);

        return  imageView;
    }

    public static void  showMedia( final Context context, final String onepic , LinearLayout pics ){
        if (!StringUtil.notNullOrEmpty(onepic)) {
            return;
        }
        FrameLayout item = (FrameLayout) LayoutInflater.from(context).inflate(R.layout.image_item, null);
        ImageView imageView  = (ImageView)item.findViewById(R.id.pic);
        Button playBtn  = (Button)item.findViewById(R.id.video_play);

        String imagePath = "";
        if (onepic.endsWith( "mp4")) {
//            imagePath = Common.getVideoSnapFile( onepic, context);
            showMP4(context,onepic,imageView);
            playBtn.setVisibility( View.VISIBLE);
            playBtn.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    Intent intent = new Intent();
                    intent.setClass(context, PlayVideoActivity.class);
                    intent.putExtra("path", onepic );
                    context.startActivity(intent );
                }
            });
        }else {
            imagePath =  onepic;
//            imageView.setOnLongClickListener(new View.OnLongClickListener() {
//                @Override
//                public boolean onLongClick(View view) {
//
//                    Intent intent = new Intent();
//                    intent.setClass(context, WebviewActivity.class);
//                    intent.putExtra("link", onepic);
//                    context.startActivity(intent);
//                    return false;
//                }
//            });

            Common.enableZoom(context,imageView,onepic);
            playBtn.setVisibility( View.GONE);
            Picasso.with(context)
                    .load(imagePath)
                    .into(imageView );

        }
        pics.addView(item);

    }


    public static void disableShiftMode(BottomNavigationView view) {
        BottomNavigationMenuView menuView = (BottomNavigationMenuView) view.getChildAt(0);
        try {
            Field shiftingMode = menuView.getClass().getDeclaredField("mShiftingMode");
            shiftingMode.setAccessible(true);
            shiftingMode.setBoolean(menuView, false);
            shiftingMode.setAccessible(false);
            for (int i = 0; i < menuView.getChildCount(); i++) {
                BottomNavigationItemView item = (BottomNavigationItemView) menuView.getChildAt(i);
                //noinspection RestrictedApi
                item.setShiftingMode(false);
                // set once again checked value, so view will be updated
                //noinspection RestrictedApi
                item.setChecked(item.getItemData().isChecked());
            }
        } catch (NoSuchFieldException e) {
            Log.e("BNVHelper", "Unable to get shift mode field", e);
        } catch (IllegalAccessException e) {
            Log.e("BNVHelper", "Unable to change value of shift mode", e);
        }
    }

    

}
